
from PySide6.QtCore import QDir, QFile
from ...PSData import *
import time
import os
from PySide6.QtWidgets import QMessageBox, QFileDialog, QWidget

class AppManageService(PSDataServer):
    '''
    Description:
        通用System服务：功能如下：
            - ProjectManage
            - TimeManage
            - AppEventManage
    '''

    # 定义类内字符串枚举
    STARTEVENT = 'StartEvent'
    STOPEVENT = 'StopEvent'
    CLOSEEVENT = 'CloseEvent'
    SAVEEVENT = 'SaveEvent'

    STARTSTATE = 'StartState'
    STOPSTATE = 'StopState'
    
    def __init__(self) -> None:
        super().__init__()
        self._state = self.STOPEVENT
        self._timeStart = time.time()
        self._setFunctionTable = {
            'SetEvent': self.SetEvent,
        }
        self._getFunctionTable = {
            'GetTime': self.GetTime,
        }
        self._currentPrjDir = str()
        self._currentPrjPath = str()
        self._currentPrjName = str()


    def SetEvent(self, data: 'PSData') -> 'bool':
        '''
        Function:
            设置APP的状态，如果设置成功就会发送Event出去
        arg:
            data.header = 'SetEvent',
            data.args = {},
            data.value = {
                'event': str(APPEvent),
            }
        '''
        event_ = data.value.get('value', None)
        if (not isinstance(event_, str)):
            return False
        if (event_ == self.STARTEVENT or 
            event_ == self.STOPEVENT):
            self.PsOnEvent(
                event = 'EventAppStatus',
                data = PSData(
                    header='EventAppStatus',
                    args={},
                    value={
                        'appEvent': event_,
                        'appTime': self._GetTime(),
                        'strTime': time.strftime("%Y-%m-%d %H:%M:%S"),
                    },
                ),
            )
        if (event_ == self.CLOSEEVENT):
            # 如果是CloseEvent，先问是否要保存
            if (not os.path.isdir(self._currentPrjDir)):
                msgbox_ = QMessageBox()
                msgbox_.setText('项目已经修改')
                msgbox_.setInformativeText('是否保存变更')
                msgbox_.setStandardButtons(QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)
                msgbox_.setDefaultButton(QMessageBox.Save)
                ret = msgbox_.exec()
                if (ret == QMessageBox.Save):
                    # 如果保存了，就弹出文件保存路径
                    res_ = QFileDialog.getSaveFileName(
                        parent=QWidget(),
                        caption='请选择需要保存的文件',
                        dir=QDir.homePath(),
                        filter='PSPrj(*.PSPrj)'
                    )
                    file_name_ = res_[0]
                    if (file_name_ != ''):
                        self._currentPrjPath = file_name_
                        self._currentPrjDir = os.path.abspath(file_name_)
                        self._currentPrjName = os.path.split(file_name_)[1]
                        self.PsOnEvent(
                            event = 'EventAppStatus',
                            data = PSData(
                                header='EventAppStatus',
                                args={},
                                value={
                                    'appEvent': self.SAVEEVENT,
                                    'appTime': self._GetTime(),
                                    'strTime': time.strftime("%Y-%m-%d %H:%M:%S"),
                                    'prjPath': self._currentPrjPath,
                                },
                            ),
                        )
                        self.PsOnEvent(
                            event = 'EventAppStatus',
                            data = PSData(
                                header='EventAppStatus',
                                args={},
                                value={
                                    'appEvent': event_,
                                    'appTime': self._GetTime(),
                                    'strTime': time.strftime("%Y-%m-%d %H:%M:%S"),
                                },
                            ),
                        )
                    else:
                        return True
                elif (ret == QMessageBox.Discard):
                    # 如果不保存，就直接发送 CloseEvent
                    self.PsOnEvent(
                        event = 'EventAppStatus',
                        data = PSData(
                            header='EventAppStatus',
                            args={},
                            value={
                                'appEvent': event_,
                                'appTime': self._GetTime(),
                                'strTime': time.strftime("%Y-%m-%d %H:%M:%S"),
                            },
                        ),
                    )
                elif (ret == QMessageBox.Cancel):
                    # 如果用户取消，什么都不做
                    return True
        return True
        
    def _GetTime(self) -> 'float':
        return time.time() - self._timeStart

    def GetTime(self, data: 'PSData') -> 'PSData':
        '''
        function:
            获取当前时间与进程运行起来的相对时间
        args:
            [in]
            data.header = 'GetTime',
            data.args = {},
            [out]
            data.value = {
                'appTime': float(从进程开起来后到现在的秒数)
                'strTime': str(当前计算机的字符串事件，用于显示)
            }
        return:
            设计文档
        '''
        data.value['appTime'] = self._GetTime()
        data.value['strTime'] = time.strftime("%Y-%m-%d %H:%M:%S")
        return data